package com.baidu.aip.demotest;

import com.baidu.aip.talker.facade.Controller;
import com.baidu.aip.talker.facade.upload.LogBeforeUploadListener;
import com.fasterxml.jackson.core.io.DataOutputAsStream;
import com.sun.media.sound.WaveFileReader;
import com.sun.media.sound.WaveFileWriter;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import javax.sound.sampled.*;
public class AudioRecorder extends JFrame {
    //https://wenku.baidu.com/view/aaf28917c5da50e2524d7fab.html


    AudioFormat audioFormat;
    TargetDataLine td;
    ByteArrayOutputStream stream1 = null;

    InputStream stream;
    private BiccTest biccTest;
    final JButton captureBtn =
            new JButton("Capture");
    final JButton stopBtn = new JButton("Stop");

    final JPanel btnPanel = new JPanel();
    final ButtonGroup btnGroup = new ButtonGroup();
    final JRadioButton aifcBtn =
            new JRadioButton("AIFC");
    final JRadioButton aiffBtn = new JRadioButton("AIFF");
    final JRadioButton auBtn = new JRadioButton("AU", true);
    final JRadioButton sndBtn = new JRadioButton("SND");
    final JRadioButton waveBtn = new JRadioButton("WAVE");

    // ----------------------------------
    ByteArrayOutputStream baos = null;
    ByteArrayInputStream bais = null;
    //定义停止录音的标志，来控制录音线程的运行
    Boolean stopflag = false;
    int n = 1;
    public static void main(String args[]) {
        new AudioRecorder();
    }


    public AudioRecorder() {
        //
        System.out.println("麦克风正在启动...");
        captureBtn.setEnabled(false);
        stopBtn.setEnabled(true);
        captureAudio();
        //Register anonymous listeners 开始按钮
        captureBtn.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        captureBtn.setEnabled(false);
                        stopBtn.setEnabled(true);

                        captureAudio();//开始录音
                    }
                }//end ActionListener
        );//end addActionListener()
        //停止 录音 button
        stopBtn.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        captureBtn.setEnabled(true);
                        stopBtn.setEnabled(false);
                        //Terminate the capturing of input data
                        // from the microphone.
                        td.stop();
                        td.close();
                        System.out.println("AudioRecorder ：recorder.td  stop :麦克风关闭");
                        n = 0;
                    }//end actionPerformed
                }//end ActionListener
        );//end addActionListener()

        //Put the buttons in the JFrame
        getContentPane().add(captureBtn);
        getContentPane().add(stopBtn);

        //Include the radio buttons in a group
        btnGroup.add(aifcBtn);
        btnGroup.add(aiffBtn);
        btnGroup.add(auBtn);
        btnGroup.add(sndBtn);
        btnGroup.add(waveBtn);


        btnPanel.add(aifcBtn);
        btnPanel.add(aiffBtn);
        btnPanel.add(auBtn);
        btnPanel.add(sndBtn);
        btnPanel.add(waveBtn);

        getContentPane().add(btnPanel);

        getContentPane().setLayout(new FlowLayout());
        setTitle("麦克风输入");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(300, 120);
        setVisible(true);
    }


    /**
     * 开始录音
     */
    private void captureAudio() {
        try {
            System.out.println("正在录音");
            //Get things set up for capture
            audioFormat = getAudioFormat();
            DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, audioFormat);
            td = (TargetDataLine) AudioSystem.getLine(dataLineInfo);


            System.out.println("td:------------"+td.isActive() + td.isRunning());
//            stream1 = new ByteArrayOutputStream();
            //新建 保存录音线程
            new CaptureThread().start();
            //新建 语音识别线程
//            Record record = new Record();
//            Thread t1 = new Thread(record);
//            t1.start();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(0);
        }
    }

    //=============================================//
    //Inner class to capture data from microphone
// and write it to an output audio file.
    //新建线程，保存录音
    class CaptureThread extends Thread {
        public void run() {
            //
            System.out.println("保存录音线程");
            AudioFileFormat.Type fileType = null;

            File audioFile = null;




            //Set the file type and the file extension
            // based on the selected radio button.
            if (aifcBtn.isSelected()) {
                fileType = AudioFileFormat.Type.AIFC;
                audioFile = new File("junk.aifc");
            } else if (aiffBtn.isSelected()) {
                fileType = AudioFileFormat.Type.AIFF;
                audioFile = new File("junk.aif");
            } else if (auBtn.isSelected()) {
                fileType = AudioFileFormat.Type.AU;
                audioFile = new File("junk.au");
            } else if (sndBtn.isSelected()) {
                fileType = AudioFileFormat.Type.SND;
                audioFile = new File("junk.snd");
            } else if (waveBtn.isSelected()) {
                fileType = AudioFileFormat.Type.WAVE;
                audioFile = new File("junk.wav");
            }//end if

            try {
                fileType= AudioFileFormat.Type.WAVE;


                 System.out.println("success____________----------:"+stream.toString());


            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    /**
     *  获取 AudioFormat 实例
     * @return
     */
    private AudioFormat getAudioFormat() {
        float sampleRate = 8000.0F;
        //8000,11025,16000,22050,44100
        int sampleSizeInBits = 16;
        //8,16
        int channels = 1;
        //1,2
        boolean signed = true;
        //true,false
        boolean bigEndian = false;
        //true,false
        return new AudioFormat(sampleRate,
                sampleSizeInBits,
                channels,
                signed,
                bigEndian);
    }//end getAudioFormat
//=============================================//
//录音类，因为要用到MyRecord类中的变量，所以将其做成内部类
    //语音识别线程
class Record implements Runnable
{

    int packageDurationInMs = 160;//发送语音间隔ms
    //定义存放录音的字节数组,作为缓冲区
    byte bts[] = new byte[packageDurationInMs*16];

    //将字节数组包装到流里，最终存入到baos中
    //重写run函数
    public void run() {
//        System.out.println("语音识别线程");
        baos = new ByteArrayOutputStream();
        try {

            stopflag = false;
            td.open(audioFormat);
            td.start();
            while(stopflag != true)
            {
                //从数据行的输入缓冲区读取音频数据。
                //要读取bts.length长度的字节,cnt 是实际读取的字节数
                int cnt = td.read(bts, 0, bts.length);

                if(cnt > 0)
                {
                    //写入到输出流中，用于保存录音
                    baos.write(bts, 0, cnt);

                    System.out.println("语音流，写入baos输入出流中");

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                //关闭打开的字节数组流
                if(baos != null)
                {
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                td.drain();
                td.close();
            }
        }
    }

}


}
